package com.cbank.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


public class ExcelUtils<T> {

	public static<T> void exportExcel(List<T> list,HttpServletResponse response, HttpServletRequest request,String fileAbstractName,Callback<T> callback)
			throws IOException {
		// 设置response参数，可以打开下载页面
		 response.reset();
		 String fileName = new String((fileAbstractName+".xls").getBytes("UTF-8"),
                 "ISO8859-1");
         fileName = fileName.replaceAll("\\+", "%20");
         response.setHeader("Cache-control", "private");
         response.setHeader("Cache-Control", "maxage=3600");
         response.setHeader("Pragma", "public");
         response.setContentType("application/vnd.ms-excel");
         response.setContentType("application/octet-stream;charset=UTF-8;");
         response.setHeader("Accept-Ranges", "bytes");
         response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
		 response.setContentType("application/octet-stream");
		 ServletOutputStream outputStream = response.getOutputStream();
		// 获取模板
		String filePath = request.getSession().getServletContext().getRealPath("/") + "/static/template/phone_list.xls";
		File file = new File(filePath);
		if (!file.exists()) {
			file.createNewFile();
		}
		FileInputStream fis = new FileInputStream(file);
		HSSFWorkbook workBook = new HSSFWorkbook(fis);
		HSSFCellStyle cellStyle = workBook.createCellStyle();
		cellStyle.setWrapText(true);
		HSSFSheet sheet = workBook.getSheetAt(0);
		// 创建行
		for (int j = 0; j < list.size(); j++) {
			HSSFRow row = sheet.createRow(j + 1);
			for (int i = 0; i < 4; i++) {
				HSSFCell cell = row.createCell(i);
				cell.setCellStyle(cellStyle);
				setData(cell, i, list.get(j),callback);
			}
		}
		workBook.write(outputStream);
		outputStream.flush();
		outputStream.close();
		fis.close();
	}

	/**
	 * @param cell 单元格
	 * @param index 第几列数据
	 * @param t 泛型对象
	 * @param callback 回调函数
	 */
	public static <T> void setData(HSSFCell cell, int index, T t,Callback<T> callback) {
		callback.setData(cell, index, t);
	}
	public static interface Callback<T>{
		void setData(HSSFCell cell, int index, T t);
	}

}
